package org.insia.smartposse.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.actions.DispatchAction;
import org.insia.smartposse.form.ProfileForm;
import org.insia.smartposse.manager.UserManager;

/**
 * @author cchalloy
 *
 */

public class ProfileAction extends DispatchAction {

	/* (non-Javadoc)
	 * @see org.apache.struts.actions.DispatchAction#dispatchMethod(org.apache.struts.action.ActionMapping, org.apache.struts.action.ActionForm, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, java.lang.String)
	 */
	@Override
	protected ActionForward dispatchMethod(ActionMapping mapping, ActionForm form, HttpServletRequest req,
			HttpServletResponse resp, String name)
	throws Exception {
		if (null != name && "" != name){
			return super.dispatchMethod(mapping, form, req, resp, name);
		} else {
			return viewProfile(mapping, form, req, resp);
		}
	}

	public ActionForward viewProfile(ActionMapping mapping, ActionForm form, HttpServletRequest req,
			HttpServletResponse resp)
	throws Exception {


		Boolean testRegister = (Boolean) req.getSession().getAttribute("registerok");

		if (null != testRegister && testRegister){
			ActionMessages messages = new ActionMessages();
			ActionMessage message = new ActionMessage("profile.goodRegister");
			messages.add("messages", message);
			saveMessages(req, messages);
			// Hide the message for After
			req.getSession().setAttribute("registerok", false);
		}

		req.setAttribute("viewProfile", true);
		req.setAttribute("profile", (UserManager) req.getSession().getAttribute("usermanager"));

		return mapping.findForward("viewProfile");
	}

	public ActionForward toUpdate(ActionMapping mapping, ActionForm form, HttpServletRequest req,
			HttpServletResponse resp) throws Exception {
		ProfileForm profileForm = (ProfileForm) form;
		UserManager user = (UserManager) req.getSession().getAttribute("usermanager");
		user.setProfile(profileForm);

		return mapping.findForward("form");
	}

	public ActionForward modifyProfile(ActionMapping mapping, ActionForm form, HttpServletRequest req,
			HttpServletResponse resp) throws Exception {
		ProfileForm profileForm = (ProfileForm) form;
		UserManager user = (UserManager) req.getSession().getAttribute("usermanager");
		user.populateProfile(profileForm);
		user.save();
		resp.sendRedirect(req.getContextPath() + "/profile.do");
		return null;
	}

}
